package vt.ece4564.phonetracker;

import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author BMW
 *
 */
public class AddRuleMapActivity extends MapActivity implements OnClickListener{
	Button plus, minus, done;
	CircleMarkerOverlay marker;
	EditText textRadius;
	MapView mapView;
    private int x;
	private int y;
	String allrules = "";

	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_rule_map);
		Intent intent = getIntent();
		allrules = intent.getStringExtra("allrules");
		
		textRadius = (EditText) findViewById(R.id.textRadius);
		plus  = (Button) findViewById(R.id.plusButton);
		minus = (Button) findViewById(R.id.minusButton);
		done  = (Button) findViewById(R.id.doneButton);
		plus.setOnClickListener(this);
		minus.setOnClickListener(this);
		done.setOnClickListener(this);
		
		//////////////////////////////////////////////////////////
		// Map setup and marker placement
		//////////////////////////////////////////////////////////
		mapView = (MapView) findViewById(R.id.mapview);
	    mapView.setBuiltInZoomControls(true);
	    List<Overlay> mapOverlays = mapView.getOverlays();
	    
	    Handler myHandler = new Handler() {

			@SuppressLint("HandlerLeak")
			@Override
	        public void handleMessage(Message msg) {
	        	x = msg.arg1;
	        	y = msg.arg2;
	        	updateCoordinates((double)x/1e6,(double)y/1e6);
	        }
	    };
	    x=37230000;
	    y=-80417778;
	    GeoPoint point = new GeoPoint(37230000, -80417778);
	    marker = new CircleMarkerOverlay(myHandler);
	    marker.geoPoint = point;
	    marker.radius = 100;	    
	    mapOverlays.add(marker);
	    MapController mc = mapView.getController();
	    mc.setZoom(18);
	    mc.animateTo(point);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.activity_hello_google_maps, menu);
		return true;
	}
	
	@Override
	protected boolean isRouteDisplayed() {
	    return false;
	}
	
	public void updateCoordinates(double longitude, double latitude){
		Context context = getApplicationContext();
		CharSequence text = "New Marker!\n" + longitude + ",\n" + latitude;
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}

	@Override
	public void onClick(View v) {
		String rad = "";
		switch(v.getId()){
		case (R.id.plusButton):
			marker.radius = marker.radius + 100;
			textRadius.getText().clear();
			rad = ""+(int)marker.radius;
			textRadius.getText().append(rad);
			//System.out.println("updating radius: " + rad);
			mapView.postInvalidate();
			break;
		case (R.id.minusButton):
			marker.radius = marker.radius - 100;
			if(marker.radius < 100)
				marker.radius = 100;
			textRadius.getText().clear();
			rad = ""+(int)marker.radius;
			textRadius.getText().append(rad);
			//System.out.println("updating radius: " + rad);
			mapView.postInvalidate();
			break;
		case (R.id.doneButton):
			//System.out.println("SAVE AND EXIT FROM THIS ACTIVITY");
			Intent intent = new Intent(this, SaveRuleActivity.class);
			intent.putExtra("rad", ""+marker.radius);
			intent.putExtra("lat", ""+x);
			intent.putExtra("long", ""+y);
			intent.putExtra("allrules", allrules);
			startActivity(intent);
			break;
		}
	}
	


private class CircleMarkerOverlay extends com.google.android.maps.Overlay {
	GeoPoint geoPoint;
	float radius;
	Handler handler;
	
	CircleMarkerOverlay(Handler handler){
		super();
		this.handler = handler;
	}

    public boolean onTap(GeoPoint p, MapView mapView) {
        geoPoint = p;
        Message msg = new Message();
        msg.arg1 = p.getLatitudeE6();
        msg.arg2 = p.getLongitudeE6();
        handler.sendMessage(msg);
        return true;
    }
	
    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow) {                              
        super.draw(canvas, mapView, shadow);
        if (!shadow) {
            Point point = new Point();
            mapView.getProjection().toPixels(geoPoint, point);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker_default);
            int x = point.x - bmp.getWidth() / 2;
            int y = point.y - bmp.getHeight();
            canvas.drawBitmap(bmp, x, y, null);  
            
            ///////////////////////////////////////////////////////////////////////
            // Circle
            /////////////////////////////////////////////////////////////////////
            
            float circleRadius =  mapView.getProjection().metersToEquatorPixels(radius);

            Paint innerCirclePaint;

            innerCirclePaint = new Paint();
            innerCirclePaint.setColor(Color.BLUE);
            innerCirclePaint.setAlpha(25);
            innerCirclePaint.setAntiAlias(true);

            innerCirclePaint.setStyle(Paint.Style.FILL);

            canvas.drawCircle((float)point.x, (float)point.y, circleRadius, innerCirclePaint);
        }

    }

}

}